/*  File Name	: Thread.cpp
 *  Author		: Pang Jiacai
 *	 E-mail		: 823960168@qq.com
 *  Created on	: 2012-9-29
 *  Description:
 */

#include "Thread.h"

Thread::Thread()
{
	this->detached_ = true;
	this->priority_ =0;
	this->thr_name_ ="";
	this->thread_id_ = 0;
	this->cb_ptr_ = NULL;
	this->cb_fun_ = NULL;
}

Thread::~Thread()
{
	this->thread_id_ = 0;
	this->cb_ptr_ = NULL;
	this->cb_fun_ = NULL;
}

int Thread::open(void *cb_ptr,thread_cb_fun cb_fun,bool detached,
		std::string thr_name,long priority)
{
	this->detached_ = detached;
	this->priority_ =priority;
	this->thr_name_ =thr_name;
	this->cb_ptr_ = cb_ptr;
	this->cb_fun_ = cb_fun;
	return 0;
}

int Thread::close(int flag)
{
	LOG((DEBUG_LOG,"Thread::close"));
	return 0;
}

int Thread::put(MessageBlock *mb)
{
	LOG((DEBUG_LOG,"Thread::put"));
	return 0;
}

int Thread::svc(void)
{
	LOG((DEBUG_LOG,"Thread::svc[%s]",this->thr_name_.c_str()));
	if(this->cb_fun_!=NULL)
	{
		this->cb_fun_(this->cb_ptr_);
	}
	return 0;
}

pthread_t Thread::activate(void)
{
	pthread_attr_t attr;
	int result = ::pthread_attr_init(&attr);
	if(result==-1)
	{
		LOG((ERROR_LOG,"Thread::activate-->pthread_attr_init error"));
		return -1;
	}
	if(this->detached_)
	{
		result=::pthread_attr_setdetachstate (&attr,PTHREAD_CREATE_DETACHED);
		if(result<0)
		{
			LOG((ERROR_LOG,"Thread::activate-->pthread_attr_setdetachstate error"));
			::pthread_attr_destroy (&attr);
			return -1;
		}
	}
	result =::pthread_create (&thread_id_,&attr,&Thread::run_svc,this);
	if(result<0)
	{
		LOG((ERROR_LOG,"Thread::activate-->pthread_create error"));
		::pthread_attr_destroy (&attr);
		return -1;
	}
	return thread_id_;
}

int Thread::wait(void)
{
	LOG((DEBUG_LOG,"Thread::wait[%s]",this->thr_name_.c_str()));
	void** status = 0;
	if(thread_id_<=0)
	{
		return 0;
	}
	return ::pthread_join(thread_id_,status);
}

const pthread_t Thread::thread_id(void)
{
	return this->thread_id_;
}

void* Thread::run_svc(void *p)
{
	Thread *thread = (Thread*)p;

	if(NULL!=thread)
	{
		thread->svc();
	}
	else
	{
		LOG((DEBUG_LOG,"Thread::run_svc point task is NULL"));
	}
	return NULL;
}
